<template>
  <basic-container>
    <avue-crud
      :option="option"
      :search.sync="search"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @sort-change="sortChange"
      @on-load="onLoad"
    >
      <template slot-scope="scope" slot="menu">
        <el-button
          icon="el-icon-picture-outline"
          size="small"
          type="text"
          @click.stop="handlePreview(scope.row.ticketQrImg)">活动宣传图
        </el-button>
        <el-button
          icon="el-icon-edit"
          size="small"
          type="text"
          @click.stop="handleEdit(scope.row, scope.index)"
          >编 辑</el-button
        >
        <el-button
          icon="el-icon-view"
          size="small"
          type="text"
          @click.stop="handleView(scope.row, scope.index)"
          >统 计</el-button
        >
        <el-button
          icon="el-icon-s-custom"
          size="small"
          type="text"
          @click.stop="handleMerchant(scope.row, scope.index)"
          >商户管理</el-button
        >
      </template>
      <template slot="menuLeft">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="small"
          @click.stop="handleSave"
          >发 券</el-button
        >
      </template>
      <template slot-scope="{ row }" slot="endDate">
        <div>{{ row.startDate }} 至 {{ row.endDate }}</div>
      </template>
      <template slot-scope="{}" slot="rpiNoSearch">
        <select-page
          ref="searchRpiSelect"
          label="rpiName"
          value="rpiNo"
          :select.sync="search.rpiNo"
          :url="website.searchLink.merchantUrl"
          placeholder-text="商户"
          filter-key="searchParam"
        ></select-page>
      </template>
      <template slot-scope="{}" slot="serviceNoSearch">
        <select-page
          ref="searchSerSelect"
          label="serviceName"
          value="serviceNo"
          :select.sync="search.serviceNo"
          :url="website.searchLink.serviceUrl"
          placeholder-text="服务商"
          filter-key="searchParam"
        ></select-page>
      </template>
      <template slot-scope="{}" slot="orgNoSearch">
        <select-page
          ref="searchOrgSelect"
          label="serviceName"
          value="serviceNo"
          :select.sync="search.orgNo"
          :url="website.searchLink.orgUrl"
          placeholder-text="机构"
          filter-key="searchParam"
        ></select-page>
      </template>
    </avue-crud>
    <el-dialog
      class="avue-dialog"
      :title="dialogText + '活动'"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      :before-close="handleClose"
    >
      <ticket-form
        :inputForm="ticketForm"
        :method="dialogType"
        ref="toticketForm"
      />
      <span slot="footer" class="dialog-footer" v-if="dialogType != 'view'">
        <el-button size="small" @click="handleSubmit" v-preventClick
          >提交</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      class="avue-dialog"
      title="商户配置"
      top="2%"
      :width="
        screenWidth > 1920
          ? '65%'
          : screenWidth <= 1920 && screenWidth > 1500
          ? '65%'
          : '80%'
      "
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="merchantDialog"
      v-if="merchantDialog"
      :before-close="handleCloseMerchant"
    >
      <merchantTables
        ref="merchantTable"
        :id="merchantForm.id"
        :rpiNo="merchantForm.rpiNo"
      ></merchantTables>
    </el-dialog>
    <el-image-viewer
        style="z-index: 99999 !important"
        v-if="payVoucherDialog"
        :on-close="()=>{ payVoucherDialog = false }"
        :url-list="[rqUrlImage]"
      ></el-image-viewer>
  </basic-container>
</template>
  
  <script>
import { getList, getDetail, add } from "@/api/rb-oem/ticket/ticket";
import { mapGetters } from "vuex";
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
import selectPage from "@/components/select-page/select-page";
import ticketForm from "./components/form/ticket-form";
import merchantTables from "./components/form/merchant-tables";

export default {
  components: {
    ElImageViewer,
    selectPage,
    ticketForm,
    merchantTables,
  },
  data() {
    return {
      form: {},
      query: {},
      search: {},
      loading: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      option: {
        height: "calc(50vh - 50px)",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        editBtn: false,
        addBtn: false,
        delBtn: false,
        selection: true,
        searchMenuSpan: 24,
        columnBtn: false,
        labelWidth: 120, //弹出表单的标题的统一宽度
        searchLabelWidth: 120, //搜索框标题宽度
        emptyBtnText: "重置",
        menuWidth: 300,
        column: [
          {
            label: "活动编号",
            prop: "ticketCode",
            type: "input",
            overHidden: true,
            minWidth: 100,
          },
          {
            label: "活动名称",
            prop: "ticketName",
            type: "input",
            search: true,
            minWidth: 150,
          },
          {
            label: "券类型",
            prop: "ticketKind",
            type: "select",
            dataType: "number",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            search: true,
            dicUrl: "/api/blade-system/dict/dictionary?code=ticket_kind",
            minWidth: 90,
          },
          {
            label: "优惠内容",
            prop: "ticketExplain",
            type: "input",
            minWidth: 150,
          },
          {
            label: "有效期",
            prop: "endDate",
            type: "input",
            minWidth: 180,
          },
          {
            label: "发放数量",
            prop: "totalCount",
            type: "input",
            search: true,
            minWidth: 90,
          },
          {
            label: "领取数量",
            prop: "receiveCount",
            type: "input",
            search: true,
            minWidth: 90,
          },
          {
            label: "使用数量",
            prop: "useCount",
            type: "input",
            search: true,
            minWidth: 90,
          },
          {
            label: "发放对象",
            prop: "givePersonType",
            type: "select",
            dataType: "number",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            search: true,
            dicUrl: "/api/blade-system/dict/dictionary?code=give_person_type",
            minWidth: 90,
          },
          {
            label: "发券状态",
            prop: "ticketStatus",
            type: "select",
            dataType: "number",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            search: true,
            dicUrl: "/api/blade-system/dict/dictionary?code=ticket_statu_kind",
            minWidth: 90,
          },
          {
            label: "创建人姓名",
            prop: "createUserName",
            type: "input",
            minWidth: 180,
          },
          {
            label: "创建时间",
            prop: "createTime",
            type: "input",
            minWidth: 150,
          },
          {
            label: "商户编号",
            searchLabel: '商户',
            search: true,
            prop: "rpiNo",
            type: "input",
            minWidth: 180,
          },
          {
            label: "商户名称",
            prop: "rpiName",
            type: "input",
            minWidth: 180,
          },
        ],
      },
      data: [],
      dialogVisible: false,
      dialogType: "", //打开类型 add/edit
      dialogText: "",
      ticketForm: {
        id: "",
        rpiNo: "",
        ticketCode: "",
        ticketName: "",
        ticketRange: 1,
        ticketRangeName: "",
        ticketType: null,
        ticketTypeName: "",
        rechargeType: null,
        rechargeTypeName: "",
        tradeAmount: "",
        discountAmount: "",
        startDate: "",
        endDate: "",
        validType: null,
        validTypeName: "",
        totalCount: null,
        personCount: null,
        receiveCount: null,
        useCount: null,
        giveLimitType: null,
        giveLimitTypeName: "",
        giveLimitCount: null,
        givePersonType: null,
        givePersonTypeName: "",
        useLimitType: null,
        useLimitTypeName: "",
        giveType: [],
        giveTypeName: "",
        ticketStatus: 1,
        ticketStatusName: "",
        ticketInstructions: "",
        useType: null,
        useRuleName: "",
        dayInterval: null,
        timeDate: [],
        rpiNos: "",
        rpiNoList: [],
        weekForm: {
          weekDay: "",
          datetimeForms: [],
        },
        dayForm: {
          dateDayForms: [],
          datetimeForms: [],
        },
        useStandard: "",
      },
      rqUrlImage: '',
      payVoucherDialog: false,
      merchantDialog: false,
      merchantForm: {
        id: "",
        rpiNo: "",
      },
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        viewBtn: this.vaildData(this.permission.summaryOfCashback_view, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    exhibition() {
      return (val) => {
        if (val == "" || val == "-1") {
          return (val = 0);
        } else {
          return val;
        }
      };
    },
  },
  methods: {
    handleSubmit() {
      this.$refs["toticketForm"].$refs["inputForm"].validate((valid) => {
        if (valid) {
          this.ticketForm.giveType = this.ticketForm.giveType.join(",");
          add(this.ticketForm).then(
            (res) => {
              this.dialogVisible = false;
              this.searchReset();
              if (res.data.code == "200") {
                this.$message({
                  type: "success",
                  message: "操作成功!",
                });
              } else {
                this.$message({
                  type: "error",
                  message: res.data.message,
                });
              }
            },
            (error) => {
              window.console.log(error);
            }
          );
        } else {
          return false;
        }
      });
    },
    /**
     * @func 新增
     * @desc 点击新增初始化显示基本信息
     * */
    handleSave() {
      this.dialogVisible = true;
      this.dialogType = "add";
      this.dialogText = "新增";
      this.ticketForm.id = null;
      this.$nextTick(() => {
        this.ticketForm = {
          id: "",
          rpiNo: "",
          ticketCode: "",
          ticketName: "",
          ticketRange: 1,
          ticketRangeName: "",
          ticketType: null,
          ticketTypeName: "",
          rechargeType: null,
          rechargeTypeName: "",
          tradeAmount: "",
          discountAmount: "",
          startDate: "",
          endDate: "",
          validType: null,
          validTypeName: "",
          totalCount: null,
          personCount: null,
          receiveCount: null,
          useCount: null,
          giveLimitType: null,
          giveLimitTypeName: "",
          giveLimitCount: null,
          givePersonType: null,
          givePersonTypeName: "",
          useLimitType: null,
          useLimitTypeName: "",
          giveType: [],
          giveTypeName: "",
          ticketStatus: 1,
          ticketStatusName: "",
          ticketInstructions: "",
          useType: null,
          useRuleName: "",
          dayInterval: null,
          timeDate: [],
          rpiNos: "",
          rpiNoList: [],
          weekForm: {
            weekDay: "",
            datetimeForms: [],
          },
          dayForm: {
            dateDayForms: [],
            datetimeForms: [],
          },
          useStandard: "",
        };
        this.$refs["toticketForm"].isTicketType = true;
      });
    },
    /**
     * @func 编辑
     * @desc 点击编辑回显基本信息
     * @param {Object} row - 表格绑定的信息
     * */
    handleEdit(row) {
      this.dialogType = "edit";
      this.dialogText = "编辑";
      getDetail({ id: row.id }).then((res) => {
        let data = res.data.data;
        this.dialogVisible = true;
        if (data.startDate && data.endDate) {
          this.$set(data, "timeDate", [data.startDate, data.endDate]);
        }
        if (data.giveType) {
          data.giveType = data.giveType.split(",");
        }
        this.$nextTick(() => {
          this.ticketForm = data;
          this.$refs["toticketForm"].isTicketType = true;
        });
      });
    },
    handleView(row) {
      this.$router.push({
        name: "单独活动统计",
        query: {
          id: row.id,
          ticketCode: row.ticketCode,
        },
      });
    },
    handlePreview(url) {
      this.rqUrlImage = url;
      this.payVoucherDialog = true;
    },
    handleMerchant(row) {
      this.merchantForm.id = row.id;
      this.merchantForm.rpiNo = row.rpiNo;
      this.merchantDialog = true;
    },
    /**
     * @func 关闭弹窗
     * @desc 点击关闭的回调
     * @param {Function} done - 完成的回调
     * */
    handleClose(done) {
      this.$refs["toticketForm"].isTicketType = false;
      this.$refs["toticketForm"].$refs["inputForm"].resetFields();
      this.onLoad(this.page, this.query);
      done();
    },
    handleCloseMerchant(done) {
      this.$refs["merchantTable"].id = "";
      this.merchantDialog = false;
      done();
    },
    /**
     * @func edit,view 打开之前回调
     * @desc 点击获取点击天数时间
     * */
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        // getDetail(this.form.id).then(res => {
        //   this.form = res.data.data;
        // });
      }
      done();
    },
    /**
     * @func 重置
     * @desc 重置查询条件
     * */
    searchReset() {
      this.query = {};
      this.search = {};
      this.onLoad(this.page);
    },
    /**
     * @func 搜索
     * @desc 根据条件查询
     * @param {params} params --- 条件查询
     * */
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    /**
     * @func 选中单元格
     * @desc 选中单元格数据
     * @param {list} list --- 选中单元格数据-数组
     * */
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    /**
     * @func 分页页码
     * @desc 分页页码改变时会触发
     * */
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      // this.refreshChange();
      this.onLoad(this.page, this.query);
    },
    /**
     * @func 当前页个数
     * @desc pageSize改变时会触发
     * */
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      // this.refreshChange();
      this.onLoad(this.page, this.query);
    },
    /**
     * @func 刷新
     * @desc 点击刷新按钮触发该事件
     * */
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    /**
     * @func 初始化
     * @desc 表格初始化查询数据
     * */
    onLoad(page, params = {}) {
      this.loading = true;
      let paramObj = Object.assign(params, this.query);
      if (!this.validatenull(paramObj.createData)) {
        paramObj.rewardTimeBegin = paramObj.createData[0] || "";
        paramObj.rewardTimeEnd = paramObj.createData[1] || "";
      }
      delete paramObj.createData;

      getList(page.currentPage, page.pageSize, paramObj).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    /**
     * @func 导出
     * @desc 根据条件导出
     * */
    handleExport() {
      let params = {
        ...this.search,
        current: "-1",
        size: "-1",
      };
      this.$confirm("是否导出用户数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        getExport(params).then(
          (res) => {
            this.$message({
              type: "success",
              message: res.data.msg,
            });
          },
          (error) => {
            window.console.log(error);
          }
        );
      });
    },
    /**
     * @func 排序
     * @desc 根据表格字段排序
     * */
    sortChange(val) {
      if (val.order == "ascending") {
        //正序
        this.query.ascs = val.prop;
        this.query.descs = "";
      } else {
        //倒序
        this.query.descs = val.prop;
        this.query.ascs = "";
      }
      this.refreshChange();
    },
  },
};
</script>
  
  <style lang="scss" scoped>
.curd-foter {
  padding-top: 10px;
  display: flex;
  flex-wrap: wrap;
}

.redFontBox {
  margin-right: 40px;
  .redFont {
    color: red;
  }
}
/deep/ .el-tag--dark.el-tag--success {
  border: none !important;
}
</style>  